<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择供应商"
    width="80%"
    :before-close="handleClose"
    destroy-on-close
  >
    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="never">
      <el-form 
        :model="searchForm" 
        :inline="true" 
        label-width="100px"
        @submit.prevent="handleSearch"
      >
        <el-form-item label="供应商名称">
          <el-input 
            v-model="searchForm.supplierName" 
            placeholder="请输入供应商名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="供应商编码">
          <el-input 
            v-model="searchForm.supplierCode" 
            placeholder="请输入供应商编码"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="供应商类型">
          <el-select 
            v-model="searchForm.supplierType" 
            placeholder="请选择供应商类型"
            clearable
            style="width: 200px"
          >
            <el-option label="工程类" value="工程类" />
            <el-option label="技服类" value="技服类" />
            <el-option label="物资类" value="物资类" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 供应商列表 -->
    <el-card class="table-card" shadow="never">
      <el-table 
        ref="supplierTableRef"
        :data="tableData" 
        v-loading="loading"
        border
        stripe
        highlight-current-row
        @current-change="handleCurrentChange"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        
        <el-table-column prop="supplierName" label="供应商名称" min-width="150" />
        
        <el-table-column prop="supplierType" label="供应商类别" width="100" align="center" />
        
        <el-table-column prop="supplierCode" label="供应商编码" width="120" align="center" />
        
        <el-table-column prop="contactPerson" label="联系人" width="100" align="center">
          <template #default="{ row }">
            <span>{{ row.contactPerson || '-' }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="phone" label="电话" width="120" align="center">
          <template #default="{ row }">
            <span>{{ row.phone || '-' }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="email" label="邮箱" min-width="150">
          <template #default="{ row }">
            <span>{{ row.email || '-' }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleConfirm"
          :disabled="!selectedSupplier"
        >
          确定选择
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { supplierService } from '../services/supplierService.js';

export default {
  name: 'SupplierSelect',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:visible', 'confirm'],
  setup(props, { emit }) {
    // 响应式数据
    const loading = ref(false);
    const tableData = ref([]);
    const selectedSupplier = ref(null);
    const supplierTableRef = ref(null);
    
    // 计算属性：对话框显示状态
    const dialogVisible = computed({
      get: () => props.visible,
      set: (val) => emit('update:visible', val)
    });
    
    // 搜索表单
    const searchForm = reactive({
      supplierName: '',
      supplierCode: '',
      supplierType: ''
    });
    
    // 分页数据
    const pagination = reactive({
      pageNum: 1,
      pageSize: 20,
      total: 0
    });

    // 获取供应商列表
    const getSupplierList = async () => {
      try {
        loading.value = true;
        const params = {
          ...searchForm,
          pageNum: pagination.pageNum,
          pageSize: pagination.pageSize
        };
        
        const response = await supplierService.getSupplierList(params);
        
        if (response.code === 200) {
          tableData.value = response.data.records || [];
          pagination.total = response.data.total || 0;
          
          // 清除之前的选择
          selectedSupplier.value = null;
          nextTick(() => {
            if (supplierTableRef.value) {
              supplierTableRef.value.setCurrentRow();
            }
          });
        } else {
          ElMessage.error(response.message || '获取供应商列表失败');
        }
      } catch (error) {
        console.error('获取供应商列表失败:', error);
        ElMessage.error('获取供应商列表失败，请稍后重试');
      } finally {
        loading.value = false;
      }
    };

    // 搜索处理
    const handleSearch = () => {
      pagination.pageNum = 1;
      getSupplierList();
    };

    // 重置处理
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = '';
      });
      pagination.pageNum = 1;
      getSupplierList();
    };

    // 表格行选择变化
    const handleCurrentChange = (row) => {
      selectedSupplier.value = row;
    };

    // 分页大小改变
    const handleSizeChange = (newSize) => {
      pagination.pageSize = newSize;
      pagination.pageNum = 1;
      getSupplierList();
    };

    // 当前页改变
    const handlePageChange = (newPage) => {
      pagination.pageNum = newPage;
      getSupplierList();
    };

    // 确认选择
    const handleConfirm = () => {
      if (!selectedSupplier.value) {
        ElMessage.warning('请选择一个供应商');
        return;
      }
      
      emit('confirm', selectedSupplier.value);
      handleClose();
    };

    // 关闭对话框
    const handleClose = () => {
      dialogVisible.value = false;
      
      // 重置数据
      selectedSupplier.value = null;
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = '';
      });
      pagination.pageNum = 1;
      tableData.value = [];
    };

    // 监听对话框显示状态
    watch(() => props.visible, (newVal) => {
      if (newVal) {
        // 对话框打开时获取数据
        getSupplierList();
      }
    });

    return {
      loading,
      tableData,
      selectedSupplier,
      supplierTableRef,
      dialogVisible,
      searchForm,
      pagination,
      getSupplierList,
      handleSearch,
      handleReset,
      handleCurrentChange,
      handleSizeChange,
      handlePageChange,
      handleConfirm,
      handleClose
    };
  }
};
</script>

<style scoped>
.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

.el-form--inline .el-form-item {
  margin-right: 20px;
  margin-bottom: 15px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}

/* 高亮选中行 */
:deep(.el-table__row.current-row) {
  background-color: #ecf5ff;
}

:deep(.el-table__row.current-row:hover) {
  background-color: #ecf5ff;
}
</style> 